﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BZ.Common.FileUtility
{
    /// <summary>
    /// 文件处理功能
    /// </summary>
    public class FileUtility
    {
        /// <summary>
        /// 是否包含文件夹
        /// </summary>
        /// <param name="_path">文件夹路径</param>
        /// <param name="_isCreateNew">如果不存在是否创建</param>
        /// <param name="_isClear">是否清空该文件夹</param>
        /// <returns>ResultInfo 返回值类型</returns>
        public static ResultInfo IsHaveDirectory(string _path, bool _isCreateNew = false, bool _isClear = false)
        {
            ResultInfo myResult = new ResultInfo(false);
            if (!string.IsNullOrEmpty(_path))
            {
                if (Directory.Exists(_path))
                {
                    myResult.IsSuccess = true;
                    myResult.Message = "";
                    if (_isClear)
                    {
                        //清空文件夹
                        Directory.Delete(_path, true);
                        Directory.CreateDirectory(_path);
                        myResult.Message = "文件夹存在，并已经被清空。";
                    }
                }
                else if (_isCreateNew)
                {
                    //建立新文件夹
                    try
                    {
                        Directory.CreateDirectory(_path);
                        myResult.IsSuccess = true;
                        myResult.Message = "文件夹创建完成。";
                    }
                    catch (Exception ex)
                    {
                        myResult.IsSuccess = false;
                        myResult.Message = ex.Message;
                    }
                }
            }
            else
            {
                myResult.IsSuccess = false;
                myResult.Message = "路径信息为空。";
            }
            return myResult;
        }

        /// <summary>
        /// 根据完整路径获取文件名（有扩展名）、子文件夹名
        /// </summary>
        /// <returns></returns>
        public static string GetEntriesNameByFullPath(string _path)
        {
            string myResult = null;
            if (!string.IsNullOrEmpty(_path))
            {
                int myIndex = _path.LastIndexOf('\\');
                if (myIndex < (_path.Length - 1))
                {
                    myResult = _path.Substring(myIndex + 1);
                }
                else
                {
                    myResult = _path;
                }
            }
            return myResult;
        }
    }
}
